const app = getApp()
const regeneratorRuntime = require('../../utils/runtime')
Page({
  data: {
    newsList: '',
    currentTag: 'top',
    newsTag: [
      {
        key: 'top',
        title: '头条'
      }, {
        key: 'shehui',
        title: '社会'
      }, {
        key: 'guonei',
        title: '国内'
      }, {
        key: 'guoji',
        title: '国际'
      },
      {
        key: 'yule',
        title: '娱乐'
      },
      {
        key: 'tiyu',
        title: '体育'
      },
      {
        key: 'junshi',
        title: '军事'
      }, {
        key: 'keji',
        title: '科技'
      },
      {
        key: 'caijing',
        title: '财经'
      },
      {
        key: 'shishang',
        title: '时尚'
      }
    ],
    newsList: []
  },
  onLoad() {
    this.initNewsList()
  },
  async onClickNewsTag(event) {
    const newsTag = event.currentTarget.dataset['tagId']
    this.setData({
      currentTag: newsTag
    })
    try {
      const news = await this.fetchNews(newsTag)
      this.setData({
        newsList: news
      })
    } catch (e) {
      wx.showToast({
        title: 'e.message',
        icon: 'none',
        duration: 2000
      })
    }
  },
  callNewsApi() {
    wx.request({
      url: 'http://v.juhe.cn/toutiao/index',
      method: 'GET',
      data: {
        type: 'top',
        key: '18fae12a082caf9753d61965ab68b042',
      },
      success(res) {
        console.log(res.data)
      }
    })
  },
  async fetchNews(newsTag) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://v.juhe.cn/toutiao/index',
        method: 'GET',
        data: {
          type: newsTag,
          key: '18fae12a082caf9753d61965ab68b042'
        },
        success(res) {
          if (res.statusCode !== 200) {
            reject(new Error('网络请求错误，请稍后再试'))
          }
          const rspBody = res.data
          const news = rspBody.result.data
          resolve(news)
        },
        fail() {
          reject(new Error('网络请求错误'))
        }
      })
    })
  },
  async initNewsList() {
    try {
      const newsList = await this.fetchNews(this.data.currentTag)
      this.setData({
        newsList
      })
    } catch (e) {
      wx.showToast({
        title: `获取新闻列表失败:${e.message}`,
        icon: 'none',
        duration: 2000
      })
    }
  }

})
